<?php

use Helper\NetworkHelper;
use Service\YarService;
use think\db;
use Orm\BaseModels;
use Core\Di;
use Core\Exception;
use Helper\StringHelper;

/**
 * user模型
 * Class UserModel
 */
class UserModel extends BaseModels
{
    /**
     * 基本字段
     * @var string
     */
    private
        $baseField = 'id,type,vipStatus,vipDeadline,mobilePhone,realname,isLoginLimit,bizUserId,bizState,yst_bind_phone,yst_bind_paypwd,special_status,yst_user_type,headImg,yst_contract_status,other_idcard_status,role,ord_role,idcard,is_supplier,is_agency';


    /**
     * 根据自定义条件获取单个用户信息
     * @param $where
     * @param string $field
     * @return array|bool
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\DbException
     * @throws db\exception\ModelNotFoundException
     */
    public function getOneData($where, $field = '')
    {
        if($field == ''){
            $field = $this->baseField;
        }
        $user = $this->where($where)->field($field)->find();
        if(!empty($user)){
            return $user->toArray();
        }
        return false;
    }


    /**
     * 获取id单个用户信息
     * @param $id
     * @param string $field
     * @return array|PDOStatement|string|\think\Model|null
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\DbException
     * @throws db\exception\ModelNotFoundException
     */
    public function getUserById($id, $field = '')
    {
        if($field == ''){
            $field = 'id,mobilePhone,vipDeadline,isLoginLimit,headImg';
        }
        $user = $this->field($field)->find($id)->toArray();
        if(empty($user)){
            return false;
        }
        $agencyVip = Db::name('agency_vip')->where([['user_id','=',$id],['end_time','>',time()],['status','=','SUCCESS']])->order('id desc')->find();
        if (!empty($agencyVip)){
            $user['vipStatus'] = 1;
        }else{
            $user['vipStatus'] = 0;
        }

        if(substr($user['headImg'],0,4)!='http'){
            $user['headImg'] = NetworkHelper::siteUrl(IMG_URL,$user['headImg']);
        }
        $card = Db::name('business_card')->where(['user_id'=>$id,'is_del'=>0])->value('id');
        $auth_data['business_card_type'] = $card ? 1: 0;//1有0没有



        return $user;
    }

    /**
     * 获取用户角色
     * @param $id
     * @return bool|string
     * @throws
     */
    public function getRoleById($id)
    {
        $user = $this->field('id,special_status,type')->find($id);
        if(!empty($user)){
            $user = $user->toArray();
            if($user['special_status'] == 3){
                if($user['type'] == 1){
                    // 精选卖家
                    return 'SPECIAL_SELLER';
                }else{
                    // 精选买家
                    return 'SPECIAL_BUYER';
                }
            }elseif($user['special_status'] == 2){
                $store = Db::name('store')
                    ->where(['userId' => $id, 'store_status' => 'PASSED','is_logoff'=>0])
                    ->find();
                if(!empty($store)){
                    // 普通卖家
                    return 'ORD_SELLER';
                }else{
                    // 普通买家
                    return 'ORD_BUYER';
                }
            }else{
                // 注册用户（未实名）
                return 'REGISTER';
            }
            return $user['role'];
        }
        return false;
    }

    /**
     * 获取当前用户角色（用户身份切换）
     * @param $id
     * @return bool|string
     * @throws
     */
    public function getCurrRoleById($id)
    {
        $user = $this->field('id,special_status,type,role,ord_role')->find($id);
        if(!empty($user)){
            $user = $user->toArray();
            if ($user['role']=='ORD_SELLER'){
                $role = 'ORD_'.$user['ord_role'];
            }else{
                $role = $user['role'];
            }
            return $role;
        }
        return false;
    }

    /**
     * 用户登录
     * @param $mobile
     * @param $password
     * @return array|bool|PDOStatement|string|\think\Model|null
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\DbException
     * @throws db\exception\ModelNotFoundException
     */
    public function checkLogin($mobile, $password)
    {
        $field = $this->baseField .',password,isLoginLimit';
        $key = Di::get('config')['secretKey']['passwordKey'];
        $user = $this->field($field)->where(['mobilePhone' => $mobile,'is_logoff'=>0])->find();
        if (!empty($user)) {
            $user = $user->toArray();
            if ($user['isLoginLimit']!=1){
                throw new \Core\Exception(10113);
            }
            if (md5($password . $key) === $user['password']) {
                unset($user['password']);
                return $user;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**
     * 获取商家信息
     * (含准企，精选流程用)
     * @param int $id
     * @return mixed
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\DbException
     * @throws db\exception\ModelNotFoundException
     */
    public function getSellerDetail($id = 1){

        $field = 't1.id,t1.realname,t1.isLegal,t1.yst_user_type,t2.company_name,t3.orgName';
        $user = $this->alias('t1')
            ->leftJoin('t_user_enterprise t2','t2.user_id = t1.id')
            ->leftJoin('t_person t3','t3.userId = t1.id')
            ->field($field)
            ->where(['t1.id' => $id])
            ->find();
        if ($user['yst_user_type']==2){
            $borrower['company_name'] = $user['company_name'];
            $borrower['shop_type'] = '2';
        }else{
            if ($user['isLegal']==1){
                $borrower['company_name'] = $user['orgName'];
                $borrower['shop_type'] = '2';
            }else{
                $borrower['company_name'] = $user['realname'];
                $borrower['shop_type'] = '1';
            }
        }
        $borrower['user_id'] = $user['id'];
        return $borrower;
    }

    /**
     * 检验手机是否已经注册
     * @param string $mobile
     * @return 1 on success or 0 or failure
     */
    public function checkMobile($mobile)
    {
        $field = array('id');
        $where = ['mobilePhone'=>$mobile,'is_logoff'=>0];
        $result = $this->Field($field)->Where($where)->find();
        if ($result) {
            return $result->toArray();
        }
        return false;
    }



    /**
     * 获取用户金钱信息
     * @param $userid
     * @return array
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\DbException
     * @throws db\exception\ModelNotFoundException
     */
    public function getUserMoney($userid)
    {

        $dueinSum = '0.00';
        $dueoutSum = '0.00';
        $agencyIncomeSum = '0.00';

        $userInfo = Db::name('user')->field('role,is_agency,is_supplier')->find();
        $UserRole = new mtyUser\UserRole();
        $userInfo['role'] = $UserRole->getUserRole($userid)['data'];
        //区分用户身份充值到不同钱包
        if (in_array('SPECIAL_SELLER',$userInfo['role']) || in_array('SPECIAL_BUYER',$userInfo['role'])){
            $wallet_special = Db::name('wallet_special')->field('duein_capital,duein_premium,dueout_capital,dueout_premium')->where(['user_id'=>$userid])->find();
            $dueinSum = number_format($wallet_special['duein_capital']+$wallet_special['duein_premium'], 2, '.', '');
            $dueoutSum = number_format($wallet_special['dueout_premium']+$wallet_special['dueout_capital'], 2, '.', '');
            $wallet = 'SPECIAL';
        }elseif (in_array('ORD_BUYER',$userInfo['role']) || in_array('ORD_SELLER',$userInfo['role'])){
            $wallet = 'ORDINARY';
            if(in_array('AGENCY',$userInfo['role'])){
                $wallet_agency = Db::name('wallet_agency')->field('duein_deposit,duein_agency_fee')->where(['user_id'=>$userid])->find();
                $agencyIncomeSum = number_format($wallet_agency['duein_deposit']+$wallet_agency['duein_agency_fee'], 2, '.', '');
                $wallet = 'AGENCY';
            }
            if(in_array('SUPPLIER',$userInfo['role'])){
                $wallet = 'SELLER';
            }
        }
        $rpc_params = [
            'user_id'    => $userid,
            'wallet_types'    => [$wallet],
        ];
        $rpcReturn1 = YarService::create("/rpc/Wallet",'getWallet', $rpc_params)['data'];
        $field = array('usableSum', 'freezeSum', 'dueinSum', 'dueoutSum','agencyIncomeSum');
        $result = $this->field($field)->find($userid);
        if ($result) {
            return [
                'usableSum' => $rpcReturn1[strtolower($wallet)]['usable_money'],
                'freezeSum' => $rpcReturn1[strtolower($wallet)]['intransit_money'],
                'dueinSum'  => $dueinSum,
                'dueoutSum' => $dueoutSum,
                'agencyIncomeSum' => $agencyIncomeSum
            ];
            return $result->toArray();
        }else{
            return [
                'usableSum' => '0.00',
                'freezeSum' => '0.00',
                'dueinSum'  => '0.00',
                'dueoutSum' => '0.00',
                'agencyIncomeSum' => '0.00'
            ];
        }
    }

    /**
     * 通过手机号码查找用户
     */
    public function getUserByMobile($mobilePhone)
    {
        $result = $this->field($this->baseField)->where(['mobilePhone' =>$mobilePhone])->find();
        if ($result) {
            return $result->toArray();
        }
        return false;
    }

    /**
     * 获取VIP情况
     */
    public function getUserVipDetail($uid){
        $result = $this->field('vipStatus,vipDeadline')->where(['id' =>$uid])->find();
        if (empty($result)) {
            return array();
        }else{
            $result = $result->toArray();
            if ($result['vipStatus'] == 2 && strtotime($result['vipDeadline']) > time()){
                //有效（未过期）
                $result['isvalid'] = true;
            }else{
                //过期或未开通
                $result['isvalid'] = false;
            }
            return $result;
        }
    }



    /**
     * 获取证件信息map
     */
    public function cardTypeMap()
    {
       return [
           '1' => ['name'=>'身份证'],
           '2' => ['name'=>'护照'],
           '4' => ['name'=>'港澳通行证'],
           '5' => ['name'=>'台胞证'],
       ];
    }


    /**
     * 获取精选卖家基础信息
     * @param $userId
     * @return array|null|PDOStatement|string|\think\Model
     * @throws db\exception\DataNotFoundException
     * @throws db\exception\DbException
     * @throws db\exception\ModelNotFoundException
     */
    public function getSellerInfo($userId){
        $data = $this->alias('t1')
            ->leftJoin('t_person t2', 't1.id=t2.userId')
            ->where(['t1.id' => $userId])
            ->field('t1.id,t1.realname,t1.mobilePhone,t1.isLegal,t2.*')
            ->find();
        if (!empty($data)){
            $data = $data->toArray();
        }
        return $data;
    }

    /**
     * 根据证件号和证件类型统计除本用户以外其他用户的数量
     * @param $userId
     * @param $idcard
     * @param $cardType
     * @return int|string
     */
    public function countUserByIdcard($userId, $idcard, $cardType)
    {
        $where = [
            ['id', '<>', $userId],
            ['idcard', '=', $idcard],
            ['cardType', '=', $cardType],
        ];
        $result = $this->where($where)->count();
        return $result;
    }

    public function getMoney($userid)
    {
        $result = $this->field('usableSum,freezeSum,dueinSum,dueoutSum')->where(['id' =>$userid])->find();
        if ($result) {
            return $result->toArray();
        }
        return FALSE;
    }



    /************ 获取器 ************/
    public function getVipDeadlineAttr($value){
        return empty($value) ? '' : date('Y-m-d', $value);
    }

    //拼接头像路径
    public function getHeadImgAttr($value){
        return empty($value) ? '/res/mobile/images/attest/default-avatar.png' : IMG_URL . $value;
    }

    //realname脱敏处理，要求同时查出yst_user_type
    public function getRealNameConvertAttr($value, $data){
        if ($data['yst_user_type'] == 1){
            return empty($value) ? $value : StringHelper::convertName($value);
        }elseif($data['yst_user_type'] == 2){
            return empty($value) ? $value : StringHelper::convertZhStr($value);
        }else{
            return $value;
        }
    }
    //mobilePhone脱敏处理
    public function getMobilePhoneConvertAttr($value){
        return empty($value) ? $value : StringHelper::convertMobile($value);
    }


    /**
     * 用户状态查询
     *
     */
    public function getUserStatus($userId){

        //实名状态
        $where = [
            'user_id'   => $userId,
            'status'    => 'PASSED',
            'is_enable' => 1,
            'is_del'    => 0,
        ];
        $authRel = Db::name('user_auth_rel')->where($where)->find();
        if (!empty($authRel)){
            $result['status'] = 'PASSED';
        }else{
            $companyApply = Db::name('user_auth_company_apply')->where(['user_id'=>$userId,'end_date'=>'9999-12-30 23:59:59'])->find();
            $authApply = Db::name('user_auth_person_apply')->where(['user_id'=>$userId,'end_date'=>'9999-12-30 23:59:59'])->find();
            if (!empty($companyApply) && !empty($authApply)){
                $result = $companyApply['create_time'] > $authApply['create_time']? $companyApply : $authApply;
            }else{
                if (!empty($authApply)){
                    $result = $authApply;
                }elseif(!empty($companyApply)){
                    $result = $companyApply;
                }else{
                    $result['status'] = 'INIT';
                }
            }

        }

        return $result;
    }

    /**
     * 获取用户实名信息
     */
    public function getUserInfo($userId,$type = ''){
        $staus = $this->getUserStatus($userId)['status'];
        if ($staus == 'AUDIT'){
            throw new Exception(20108);
        }
        if ($staus == 'REFUSED'){
            throw new Exception(20109);
        }
        if ($staus!='PASSED'){
            throw new Exception(21025);
        }
        //实名状态
        $where = [
            'user_id'   => $userId,
            'is_enable' => 1,
            'is_del'    => 0,
        ];
        !empty($type)&&$where['type'] = $type;
        $authRel = Db::name('user_auth_rel')->where($where)->order('id desc')->find();
        $info = Db::name('user_auth_'.strtolower($authRel['type']))->where(['id'=>$authRel['auth_id']])->find();



        return $info;
    }

}
